package com.gugugu.web.rpc.aware.server;

import com.gugugu.web.rpc.annotion.GuRpcService;
import com.gugugu.web.rpc.server.NettyRpcServerForSpringBoot;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


import java.util.Map;


@Component
@Slf4j
public class GuRpcServerAware implements ApplicationContextAware, InitializingBean {
    // RPC服务实现容器
    @Autowired
    private NettyRpcServerForSpringBoot rpcServer;

     @Override
     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
         Map<String, Object> services = applicationContext.getBeansWithAnnotation(GuRpcService.class);
         log.info("该服务能注册的消费者个数 ：{}",services.size());
         for (Map.Entry<String, Object> entry : services.entrySet()) {
             Object bean = entry.getValue();
             Class<?>[] interfaces = bean.getClass().getInterfaces();
             for (Class<?> inter : interfaces) {
                 rpcServer.publishService(bean,inter.getName());
                 log.info("加载GuRpcService :{} , 接口 ： {}",bean,inter);
             }
         }
    }
    @Override
    public void afterPropertiesSet() {
        new Thread(() -> {
            rpcServer.start();
        }).start();
    }

}